import React, {FC, useEffect, useState} from "react";
import {
  AutoComplete,
  Button,
  Checkbox,
  Form,
  message,
  Popconfirm,
  Result,
  Space,
  Tree,
  TreeProps
} from "antd";
import {add, getFilterOne, update} from "@/pages/filter/service";
import {DeleteOutlined, ArrowDownOutlined, EditOutlined, PlusOutlined, ArrowUpOutlined} from "@ant-design/icons";
import {useRequest} from "@@/exports";
import {BetaSchemaForm, ProFormColumnsType} from "@ant-design/pro-components";
import {getSettingList} from "@/pages/public-setting/service";

const updateCheckedStatus = (ret: any[], checkedKeys: any[] = []) => {
  ret.forEach((item: any) => {
    if (checkedKeys.includes(item.key)) {
      item.isShow = true
    } else {
      item.isShow = false
    }
    if (item.children) {
      updateCheckedStatus(item.children, checkedKeys)
    }
  })
}

interface CustomRootTreeDataProps {
  cascaderVal: any[]
  treeData: any[]
  setTreeData: any
  onLoading?: any
}

const CustomRootTreeData: FC<CustomRootTreeDataProps> = ({
                                                           cascaderVal = [],
                                                           treeData = [],
                                                           setTreeData,
                                                           onLoading,
                                                         }) => {
  const [addForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  const initalCheckedKeys = (ret: any[], checkedKeys: any[] = []) => {

    ret.forEach((item: any) => {
      if (item.isShow) {
        checkedKeys.push(item?.key || item?.value)
      }
      if (item.children) {
        initalCheckedKeys(item.children, checkedKeys)
      }
    })

    return checkedKeys
  }

  // 筛选条件
  const {loading, refresh: loadTreeData} = useRequest(async () => {
    let res = await getFilterOne({
      categoryId: cascaderVal[cascaderVal?.length - 1],
    });

    // console.log('res', res);

    if (!res?.data) {
      setTreeData([])
      return
    }

    const value = res?.data?.value
    let ret = []
    try {
      ret = JSON.parse(value)?.filter?.((item: any) => !!item)?.map((item: any) => ({
        ...item,
        title: item.name,
        key: item?.fieldName
      }))?.sort((a: any, b: any) => a.sort - b.sort)
      // console.log('ret', ret)
      setTreeData(ret)
      const keys = initalCheckedKeys(ret)
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      setCheckedKeys(keys)
    } catch (e) {
    }
    return res;
  }, {
    refreshDeps: [cascaderVal],
  });

  const handleSave = async (values?: any) => {
    const hide = message.loading('正在保存');

    try {
      const {data: filterOne} = await getFilterOne({
        categoryId: cascaderVal[cascaderVal?.length - 1],
      })
      // console.log(filterOne);
      if (filterOne?.id) {
        if (values) {
          if (values?.key) {
            // eslint-disable-next-line no-param-reassign
            treeData = treeData?.map(item => {
              if (item.key === values?.key) {
                // eslint-disable-next-line no-param-reassign
                item = {
                  ...values
                }
              }
              return item
            })
          } else {
            treeData.push(values)
          }
        }
        await update({
          id: filterOne?.id,
          categoryId: cascaderVal[cascaderVal?.length - 1],
          name: `${cascaderVal[cascaderVal?.length - 1]}-分类-筛选条件`,
          value: JSON.stringify(treeData)
        })
      } else {
        if (values) {
          treeData.push(values)
        }
        await add({
          categoryId: cascaderVal[cascaderVal?.length - 1],
          name: `${cascaderVal[cascaderVal?.length - 1]}-分类-筛选条件`,
          value: JSON.stringify(treeData)
        })
      }

      setTreeData([...treeData])

      hide();
      loadTreeData()
      message.success('保存成功');
      return true
    } catch (e) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  }

  useEffect(() => {
    onLoading?.(loading)
  }, [loading])

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    // console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const delChild = (data: any[], key: any) => {
    data.forEach((item, index) => {
      if (item.key === key) {
        data.splice(index, 1)
      }
      if (item.children) {
        delChild(item.children, key)
      }
    })
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleDel = async (record: any = null, values: any = null) => {
    const hide = message.loading('正在删除');

    try {
      const {data: filterOne} = await getFilterOne({
        categoryId: cascaderVal[cascaderVal?.length - 1],
      })
      // console.log(filterOne);
      let newTreeData = [...treeData]
      delChild(newTreeData, record?.key)
      // console.log('newTreeData', newTreeData);

      if (filterOne?.id) {
        await update({
          id: filterOne.id,
          categoryId: cascaderVal[cascaderVal?.length - 1],
          name: `${cascaderVal[cascaderVal?.length - 1]}-分类-筛选条件`,
          value: JSON.stringify(newTreeData)
        })
      } else {
        return false
      }

      setTreeData([...newTreeData])

      hide();
      message.success('删除成功');
      return true
    } catch (e) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue, info) => {
    // console.log('onCheck', checkedKeysValue, info, treeData);
    // info.checkedNodes.forEach((item: any) => {
    //   item.checked = true
    // })
    // setRightOps([...rightOps])
    setCheckedKeys(checkedKeysValue as React.Key[]);
    updateCheckedStatus(treeData, checkedKeysValue as React.Key[])
    setTreeData([...treeData])
    handleSave()
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const onSelect: TreeProps['onSelect'] = (selectedKeysValue, info) => {
    // console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  const [options, setOptions] = useState<any[]>([])
  const {data: settingInfo} = useRequest(async () => {
    const res = await getSettingList()
    const newVal: any = {}
    Object.keys(res?.data).forEach((key) => {
      try {
        newVal[key] = JSON.parse(res?.data[key]?.value || '')
      } catch (e) {
      }
    })
    newVal.publicFilteringCriteria = newVal?.publicFilteringCriteria?.map((item: any) => ({
      ...item,
      label: `${item.name}(${item.fieldName})`,
      value: item.fieldName
    })) || []

    return {
      data: newVal
    }
  }, {
    onSuccess(data) {
      setOptions(data?.publicFilteringCriteria)
    },
  });
  const columns: ProFormColumnsType<any, any>[] = [
    {
      title: '排序',
      dataIndex: 'sort',
      valueType: 'digit',
      initialValue: addForm.getFieldsValue()?.home_grid?.length + 1 || 0,
      width: 120,
    },
    {
      title: '名称',
      dataIndex: 'title',
    },
    {
      title: '字段名',
      dataIndex: 'fieldName',
      renderFormItem() {
        return <AutoComplete
          options={options}
          // style={{ width: 200 }}
          // onSelect={onSelect}
          onSearch={(text) => {
            const newOptions = settingInfo?.publicFilteringCriteria.filter((item: any) => item.value?.indexOf(text) !== -1)
            setOptions(newOptions)
          }}
          placeholder="请输入字段名"
        />
      }
    },
    {
      title: '筛选类型',
      dataIndex: 'filterType',
      valueType: 'select',
      valueEnum: {
        range: {text: '范围筛选'},
        value: {text: '值筛选'}
      }
    },
    {
      title: '是否显示',
      dataIndex: 'isShow',
      valueType: 'switch',
      initialValue: true,
      fieldProps: {
        unCheckedChildren: '隐藏',
        checkedChildren: '显示'
      },
      // width: '40%',
    },
  ]

  return <>
    {treeData?.length > 0 ? <>
      <div style={{marginLeft: 10}}>
        <BetaSchemaForm<any>
          layoutType={'ModalForm'}
          onFinish={async (values) => {
            //根据字段名去重
            const target = treeData?.find(item => item.fieldName === values?.fieldName)
            // console.log('target', target)
            if(target) {
              message.warning('字段名重复，请修改后再试!')
              return false
            }
            return handleSave(values);
          }}
          form={addForm}
          modalProps={{
            destroyOnClose: true,
            title: "增加筛选条件",
            width: "500px",
          }}
          trigger={
            <Button
              type={'link'}
              onClick={() => {
                // setCurrentData(record)
                // console.log('record', record);
                addForm.setFieldsValue({})
              }}
              icon={<PlusOutlined/>}>新增筛选条件</Button>
          }
          columns={columns}
        />

      </div>
      <Checkbox
        checked={treeData?.every((item: any) => item?.isShow)}
        style={{marginLeft: 24, marginBottom: 5}}
        onChange={async (e) => {
          // console.log(`checked = ${e.target.checked}`, treeData);
          if (e.target.checked) {
            const checkedKeysValue = treeData?.map((item: any) => item.key)
            setCheckedKeys(checkedKeysValue)
            updateCheckedStatus(treeData, checkedKeysValue as React.Key[])
            setTreeData([...treeData])
            await handleSave()
          } else {
            setCheckedKeys([])
            updateCheckedStatus(treeData, [] as React.Key[])
            setTreeData([...treeData])
            await handleSave()
          }
        }}>
        <span style={{paddingLeft: 4}}>全选/取消全选</span>
      </Checkbox>
      <Tree
        style={{background: 'rgba(223, 223, 223,.17)'}}
        checkable
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        treeData={treeData}
        titleRender={(record: any) => {
          return <Space size={12}>
            <span>{record?.title || '-'}({record?.fieldName || '-'})</span>
            <a onClick={() => {
              const current = treeData?.find(item => item.key === record?.key)
              const currentIndex = treeData?.findIndex(item => item.key === record?.key)
              if(currentIndex <= 0) {
                return
              }
              // console.log('current', current, currentIndex)
              const tem = {...treeData?.[currentIndex-1]}
              treeData[currentIndex-1] = current
              treeData[currentIndex] = tem
              setTreeData([...treeData]?.map((item, index) => ({...item, sort: index})))
              handleSave()
            }}><ArrowUpOutlined/></a>
            <a onClick={() => {
              const current = treeData?.find(item => item.key === record?.key)
              const currentIndex = treeData?.findIndex(item => item.key === record?.key)
              if(currentIndex >= treeData?.length - 1) {
                return
              }
              // console.log('current', current, currentIndex)
              const tem = {...treeData?.[currentIndex+1]}
              treeData[currentIndex+1] = current
              treeData[currentIndex] = tem
              setTreeData([...treeData]?.map((item, index) => ({...item, sort: index})))
              handleSave()
            }}><ArrowDownOutlined/></a>
            <BetaSchemaForm<any>
              layoutType={'ModalForm'}
              onFinish={async (values) => {
                // console.log('values', values, record)
                return handleSave({...record, ...values});
              }}
              form={editForm}
              modalProps={{
                destroyOnClose: true,
                title: "编辑筛选条件",
                width: "500px",
              }}
              trigger={
                <a
                  type={'link'}
                  onClick={() => {
                    // setCurrentData(record)
                    // console.log('record', record);
                    editForm.resetFields()
                    editForm.setFieldsValue({...record})
                  }}
                ><EditOutlined/></a>
              }
              columns={columns}
            />
            <Popconfirm
              title="删除列"
              description={<>
                <p>确认删除 <b>{record?.name}</b> 筛选项?</p>
              </>}
              onConfirm={async () => {
                const isOk = handleDel(record)
                return isOk;
              }}
              okText="是"
              cancelText="否"
            >
              <a><DeleteOutlined/></a>
            </Popconfirm>
          </Space>
        }}
      />
    </> : (!loading ? <Result
      title={'该一级分类暂无筛选条件，点击按钮新增'}
      extra={<Space key={'space'}>
        <BetaSchemaForm<any>
          layoutType={'ModalForm'}
          onFinish={async (values) => {
            return handleSave(values);
          }}
          form={addForm}
          modalProps={{
            destroyOnClose: true,
            title: "增加筛选条件",
            width: "500px",
          }}
          trigger={
            <Button type={'primary'} icon={<PlusOutlined/>} onClick={() => {

            }}>新增筛选条件</Button>
          }
          columns={columns}
        />
      </Space>
      } style={{margin: 'auto'}}/> : <></>)}
  </>
}

export default CustomRootTreeData
